
import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:single/event/door_status_event.dart';
import '../entity/book_entity.dart';
import '../entity/current_task_entity.dart';
import '../main.dart';
import '../util/timer_manager.dart';
import '../widget/auth_dialog.dart';
import 'borrow_result_page.dart';


class BookDetail extends StatefulWidget {
  const BookDetail({Key? key}) : super(key: key);

  @override
  State<BookDetail> createState() => _BookDetailState();
}

class _BookDetailState extends State<BookDetail> {

  late BookEntity bookEntity;

  StreamSubscription? lockSubscription;

  var timer = TimerManager();


  @override
  initState() {
    super.initState();

    bookEntity = Get.arguments;

    lockSubscription = eventFactory.on<DoorStatusEvent>().listen((event) {
      if(!event.isOpen && currentTask.uid != null){
        Get.to(() => const BorrowResult());
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.normal,(){
        Get.until((route) => route.isFirst);
      });
    });

  }

  @override
  void dispose() {
    lockSubscription?.cancel();
    lockSubscription = null;
    super.dispose();
  }


  _title(){
    return Container(
        margin: EdgeInsets.only(top:10.h,left: 12.w,right: 12.w),
        width: double.infinity,
        height: 60.h,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [

            Positioned(
              left: 0,
              child:  InkWell(
                onTap: (){
                  timer.cancel();
                  Get.back();
                },
                child: Image.asset("assets/images/back.png",width:80.w, fit: BoxFit.fitWidth,),
              ),
            ),
            Text("书籍详情",style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 16.sp,fontWeight: FontWeight.bold),),
            Positioned(
                right: 0,
                child:Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
            ),
          ],
        )
    );
  }

  _booksCover(){
    return Align(
        child: bookEntity.cover!= ''?Image.memory(base64Decode(bookEntity.cover??''),
          gaplessPlayback: true,//防止重绘
          width: 83.w,
          height: 105.h,
          fit: BoxFit.cover,
        ):Image.asset("assets/images/default.jpg",height: 105.h, width: 83.w, fit: BoxFit.fill,),
    );
  }

  _coverBg(){
    return Container(
      decoration:BoxDecoration(
        color: const Color.fromRGBO(242,254, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(8.r),topRight:Radius.circular(8.r)),
      ),
      width: double.infinity,
      height: 100.h,
    );
  }

  _booksContainer(){
    return Container(
      decoration:const BoxDecoration(
        color: Color.fromRGBO(242,254, 255, 1),
      ),
      padding: EdgeInsets.only(left: 30.w,right: 30.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Align(child: Text(bookEntity.mainTitle??'',style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w500),)),
          Align(child:  Text(bookEntity.author??'',style: TextStyle(fontSize: 10.sp,color: Colors.black),)),
          Text('作品简介',style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w500),),

          SizedBox(
            width: 350.w,
            height: 200.h,
            child: Text('${bookEntity.summary}',style: TextStyle(fontSize: 10.sp,color: Colors.black),maxLines: 10, overflow: TextOverflow.ellipsis,),
          ),

          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('ISBN: ',style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w500),),
              Text(bookEntity.isbn??'',style: TextStyle(fontSize: 10.sp,color: Colors.black),),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('索书号: ',style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w500),),
              Text(bookEntity.searchNo??'',style: TextStyle(fontSize: 10.sp,color: Colors.black),),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text('条码: ',style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w500),),
              Text(bookEntity.no??'',style: TextStyle(fontSize: 10.sp,color: Colors.black),),
            ],
          ),
          Align(
            child: InkWell(
              onTap: (){
                currentTask.task = Task.borrow;
                AuthDialog().authTypeDialog();
              },
              child: Image.asset("assets/images/to_borrow.png", width:250.w, fit: BoxFit.fitWidth,),
            ),
          )
        ],
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Stack(
              children: [
                ImageFiltered(
                  imageFilter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
                  child: bookEntity.cover!= ''?Image.memory(base64Decode(bookEntity.cover??''),
                    gaplessPlayback: true,
                    width: double.infinity,
                    height: 210.h,
                    fit: BoxFit.cover,
                  ):Image.asset("assets/images/default.jpg",width:  double.infinity, height: 200.h, fit: BoxFit.cover,),
                ),
                _title(),
                Positioned(
                  top: 160.h,
                  height: 120.h,
                  left: 0,
                  right: 0,
                  child: _coverBg()
                ),
                Positioned(
                  top: 100.h,
                  left: 0,
                  right: 0,
                  child: _booksCover()
                )

              ],
            ),

            _booksContainer()


          ],
        ),
      ),
    );
  }
}

